package com.me.uniplugin;

import static android.content.Context.MEDIA_PROJECTION_SERVICE;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 插件入口类
 * 一个页面初始化一次, 初始化完毕之后才能获取到上下文
 */
public class RecordModule extends UniModule {
    private static final int CODE_REQUEST_RECORD = 1;
    private static final int CODE_PERMISSION_RECORD = 2;
    private MediaProjectionManager mMediaProjectionManager;
    private UniJSCallback startRecordCallback;
    private String recordPath;
    private JSONObject optionRecord;
    private boolean isAllowRecord = true;
    private boolean isRecording = false;


    /**
     * 获取上下文
     */
    public Context getContext(){
        return mUniSDKInstance.getContext();
    }

    public Activity getActivity(){
        return (Activity) getContext();
    }

    //run ui thread
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
        Log.e("NewRecordModule", "testAsyncFunc--"+options);
        if(callback != null) {
            JSONObject data = new JSONObject();
            data.put("code", "success");
            callback.invoke(data);
        }
    }

    /**
     * 开始录屏 - 异步回调结果 uiThread = true
     */
    @UniJSMethod(uiThread = true)
    public void startRecord(JSONObject options, UniJSCallback callback) {
        startRecordCallback = callback;
        if(!isAllowRecord){
            startRecordCallback(504, "当前窗口禁止录屏");
            return;
        }
        if(isRecording){
            startRecordCallback(505, "已在录屏中");
            return;
        }
        optionRecord = options;
        // 检查录屏权限
        if(!checkRecordPermission()) return;
        // 申请录屏服务
        requestRecord();
    }

    /**
     * 开始录屏的回调
     */
    private void startRecordCallback(int code, String msg) {
        if(startRecordCallback != null) {
            JSONObject data = new JSONObject();
            data.put("code", code);
            data.put("msg", msg);
            startRecordCallback.invoke(data);
            startRecordCallback = null;
        }
    }

    /**
     * 申请录屏服务
     */
    private void requestRecord(){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            startRecordCallback(501, "您的系统不支持录屏功能");
            return;
        }
        if(mMediaProjectionManager == null) mMediaProjectionManager = (MediaProjectionManager) getActivity().getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        getActivity().startActivityForResult(captureIntent, CODE_REQUEST_RECORD);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_RECORD && resultCode == Activity.RESULT_OK) {
            // 录屏文件地址
            recordPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/" + System.currentTimeMillis() + ".mp4";
            // 允许录屏之后,开启录屏Service
            Intent recordService = new Intent(getActivity(), RecordService.class);
            recordService.putExtra("resultCode", resultCode);
            recordService.putExtra("data", data);
            recordService.putExtra("recordPath", recordPath);
            if(optionRecord != null){
                recordService.putExtra("ratio", optionRecord.getIntValue("ratio"));
                recordService.putExtra("frame", optionRecord.getIntValue("frame"));
                recordService.putExtra("isAudio", optionRecord.getBooleanValue("isAudio"));
            }
            getActivity().startService(recordService);
            // 成功回调
            startRecordCallback(0, "开始录屏");
            isRecording = true;
        } else {
            // 失败回调
            startRecordCallback(503, "您已拒绝录屏操作");
        }
    }

    /**
     * 检查录屏权限
     */
    private boolean checkRecordPermission() {
        Activity activity = getActivity();
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission =
                    ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_PERMISSION_RECORD);
                return false;
            }
        }
        return true;
    }

    /**
     * 权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == CODE_PERMISSION_RECORD){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // 同意授权, 继续录屏
                requestRecord();
            }else{
                // 拒绝授权
                startRecordCallback(502, "您已拒绝录屏权限");
            }
        }
    }

    /**
     * 结束录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public JSONObject stopRecord() {
        JSONObject data = new JSONObject();
        if(isRecording){
            isRecording = false;
            Intent service = new Intent(getActivity(), RecordService.class);
            getActivity().stopService(service);
            data.put("code", 0);
            data.put("msg", "录制成功");
            data.put("path", recordPath);
        }else{
            data.put("code", 501);
            data.put("msg", "您还未开始录屏");
        }
        return data;
    }

    /**
     * 禁止录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public void noRecord() {
        isAllowRecord = false;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    /**
     * 允许录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public void allowRecord() {
        isAllowRecord = true;
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }
}
